package br.com.onlinebidding.facade;

import java.util.List;

import br.com.onlinebidding.dao.UserDAO;

import br.com.onlinebidding.model.User;

public class UserFacade {
	
	private UserDAO userDAO = new UserDAO();

	public User isValidLogin(String email, String password) {
		userDAO.beginTransaction();
		User user = userDAO.findUserByEmail(email);

		if (user == null || !user.getPassword().equalsIgnoreCase(password)) {
			return null;
		}
		return user;
	}
	
	public void insertUser(User user) {
		this.userDAO.beginTransaction();
		this.userDAO.save(user);
		this.userDAO.commitAndCloseTransaction();
	}

	public void updateUser(User user) {
		this.userDAO.beginTransaction();
		User persistedUser = this.userDAO.find(user.getId());
		persistedUser.setName(user.getName());
		persistedUser.setPassword(user.getPassword());
		persistedUser.setEmail(user.getEmail());
		persistedUser.setNumberRegistration(user.getNumberRegistration());
		persistedUser.setProfile(user.getProfile());
		persistedUser.setTelephone(user.getTelephone());
		this.userDAO.update(persistedUser);
		this.userDAO.commitAndCloseTransaction();
	}

	public User findUser(int userId) {
		this.userDAO.beginTransaction();
		User user = this.userDAO.find(userId);
		this.userDAO.closeTransaction();
		return user;
	}

	public List<User> listAll() {
		this.userDAO.beginTransaction();
		List<User> result = this.userDAO.findAll();
		this.userDAO.closeTransaction();
		return result;
	}

	public void deleteUser(User user) {
		this.userDAO.beginTransaction();
		User persistedUser = this.userDAO.findReferenceOnly(user.getId());
		this.userDAO.delete(persistedUser);
		this.userDAO.commitAndCloseTransaction();
	}
}